#include "../lib/led.h"

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>
#include <sys/time.h>
#include <signal.h>

static led_t *led_custom;

/**
 * @brief 定时运行翻转LED
 * @param sig 
 * @author he (heweilong@huchuang.com)
 * @date 2025-08-04
 * @note
 */
void timeout_handler(int sig)
{
	static bool status_led_sys = false;
	if (led_write(led_custom, status_led_sys) < 0)
	{
		fprintf(stderr, "led_write(): %s\n", led_errmsg(led_custom));
		exit(1);
	}
	else
	{
		printf("led_custom STA %d\r\n", status_led_sys);
		status_led_sys = !status_led_sys;
	}
}

/**
 * @brief 退出程序回调
 * @param sig 
 * @author he (heweilong@huchuang.com)
 * @date 2025-08-04
 * @note
 */
void ctrl_c_handle(int sig)
{
	printf("CTRL + C cb\r\n");

	struct itimerval disable = {0};
	setitimer(ITIMER_REAL, &disable, NULL);
	printf("Timer disabled\n");

	led_close(led_custom);
	led_free(led_custom);
	printf("led_custom free\n");

	exit(0);
}


int main(void)
{
	printf("led demo \r\n");

	/* 打开LED */
	led_custom = led_new();
	if (led_open(led_custom, "custom_led") < 0)
	{
		fprintf(stderr, "led_open(): %s\n", led_errmsg(led_custom));
		exit(1);
	}

	/*初始化定时器定时反转*/
	signal(SIGALRM, timeout_handler);
	struct itimerval timer = {
		.it_value = {.tv_sec = 1, .tv_usec = 0},		// 首次触发 1秒
		.it_interval = {.tv_sec = 1, .tv_usec = 0}	// 触发周期 1秒
	};
	setitimer(ITIMER_REAL, &timer, NULL); // 启动定时器

	/*CTRL+C 回调*/
	signal(SIGINT, ctrl_c_handle);
	
	while (1)
	{
		sleep(1);
	}
	
	return 0;
}
